package com.boomsecret.utils;

import org.apache.commons.lang3.StringUtils;
import java.security.MessageDigest;

/**
 * Created by wangjinliang on 2018/4/12.
 */
public final class Md5Util {
    private final static String[] hexDigits = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };

    private final static String salt = "salt";

    private final static String algorithm = "MD5";

    private Md5Util() {}

    public static String md5(String raw) {
        if (StringUtils.isEmpty(raw)) {
            return null;
        }
        try {
            MessageDigest md = MessageDigest.getInstance(algorithm);
            byte[] bytes = md.digest((raw + salt).getBytes("utf-8"));
            return byteArrayToHexString(bytes);
        } catch (Exception ex) {
            return null;
        }
    }

    private static String byteArrayToHexString(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (int index = 0; index < bytes.length; index ++) {
            sb.append(byteToHexString(bytes[index]));
        }
        return sb.toString();
    }

    private static String byteToHexString(byte itemByte) {
        int n = itemByte;
        if (n < 0)
            n = 256 + n;
        int d1 = n / 16;
        int d2 = n % 16;
        return hexDigits[d1] + hexDigits[d2];
    }
}